<?php
/*
 * @Author: 李明
 * @Date: 2022-01-10 11:12:19
 * @LastEditTime: 2022-01-22 10:01:59
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/AllInPay/BankCardAuth.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\AllInPay;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\FddVerifySDK\FddUtils;
use App\Models\FamiliesMoneyRecord;
use App\Http\Controllers\Utils;
use App\Http\Resources\TL\TLPay;
use App\Models\BankCard;
use App\Models\InterestRecord;
use App\Models\Order;
use App\Models\OrderRecord;
use App\Models\TlAuth;
use App\Models\TlBankCompany;
use App\Models\TlPayList;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

use Illuminate\Support\Facades\Storage;
use function PHPUnit\Framework\isNull;

class BankCardAuth extends Controller
{
    /**
     * @description: 查询当前可用公户
     * @param {*}
     * @return {*}
     */
    public function CompanyAccount(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCACA1');
        }
        try {
            $where = [];
            $where[] = ['type', 1];
            $company_account_list = TlBankCompany::where($where)->get();
            return LMReturn::Success($company_account_list);
        } catch (\Throwable $th) {
            return LMReturn::Error('入库时发生意外', 'BCACA2');
        }
    }
    /**
     * @description: 用户修改付款状态
     * @param {Request} $request
     * @return {*}
     */
    public function FinshOrderPayTL(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $order_id = $all['order_id'];
            $type = $all['type'] ?? 1; // 1是改成已付款  2 是改成未付款
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCAFORPT3');
        }
        try {
            $order = Order::find($order_id);
            if ($type == 1) {
                if ($order->investment_way == 2) {
                    $order->investment_way = 3;
                } else {
                    return LMReturn::Error('该订单不允许这样操作', 'BCAFORPT1');
                }
            } else {
                if ($order->investment_way == 3) {
                    $order->investment_way = 2;
                } else {
                    return LMReturn::Error('该订单不允许这样操作', 'BCAFORPT4');
                }
            }
            $order->save();
            return LMReturn::Success($order);
        } catch (\Throwable $th) {
            return LMReturn::Error('入库时发生意外', 'BCAFORPT2');
        }
    }
    /**
     * @description: 解绑/绑定 通联付款记录
     * @param {Request} $request
     * @return {*}
     */
    public function TLOrderFinance(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $order_id = $all['order_id'] ?? 0;
            $tl_pay_id = $all['tl_pay_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCATPL2');
        }
        try {
            $tl_pay = TLPayList::find($tl_pay_id);
            if ($order_id == 0) {
                $tl_pay->order_id = null;
            } else {
                $tl_pay->order_id = $order_id;
            }
            $tl_pay->save();
            return LMReturn::Success($tl_pay);
        } catch (\Throwable $th) {
            return LMReturn::Error('入库时发生意外', 'BCATPL1');
        }
    }
    /**
     * @description: 查询入账记录
     * @param {Request} $request
     * @return {*}
     */
    public function TLPayList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $order_id = $all['order_id'] ?? 0;
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCATPL2');
        }
        try {
            $bank_card_list = Order::find($order_id)->user->bank_cards ?? [];
            $bc_id_list = [];
            foreach ($bank_card_list as $bank_card) {
                $bc_id_list[] = $bank_card->bank_num;
            }
            $tl_list = TLPayList::where('order_id', $order_id)->get();
            $tl_list_null = TLPayList::whereNull('order_id')->whereIn('acct_num', $bc_id_list)->get();
            $res['tl_list'] = TLPay::collection($tl_list);
            $res['tl_list_null'] = TLPay::collection($tl_list_null);
            return LMReturn::Success($res);
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCATPL1');
        }
    }
    /**
     * @description: 第一步：快捷开户接口
     * @param {Request} $request
     * @return {*}
     */
    public function BankCardSubmitAuth(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $bank_card_id = $all['bank_card_id'];
            $phone_num = $all['phone_num'];
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCABCSA1');
        }
        // 整理 上传参数
        try {
            $bank_card = BankCard::find($bank_card_id);
            if ($bank_card->status == 3) {
                return LMReturn::Error('当前银行卡已认证', 'BCABCSA5');
            }
            $user = $bank_card->user;
            $time_int = time();
            $post_data['req_trace_num'] = $bank_card_id . $time_int; //2：机构请求交易流水号
            $post_data['bnk_id'] = $bank_card->bank->bnk_id ?? '03040000'; //银行编码
            $post_data['bnk_id'] = '03040000'; //  03040000测试用华夏银行
            $post_data['sign_type'] = "2"; //2：快捷签约
            $post_data['hld_name'] = $bank_card->account_name; //户名
            $post_data['acct_type'] = "1"; //1：借记卡 2：贷记卡
            $post_data['acct_num'] = $bank_card->bank_num; //卡号
            // $post_data['acct_num'] = '1234551871453476580'; // 测试卡bin规则：123455+13位数字且不以9结尾
//            switch ($user->id_type) { //01：身份证 其他类型详见5.2证件类型字典
//                case '1':
//                    $id_type = "01";
//                    break;
//                default:
//                    $id_type = "01";
//                    break;
//            }
            if ($user->id_type == 1) {
                $id_type = "01";
            } else {
                return LMReturn::Error('目前只支持身份证注册用户进行快捷开户，如需开户请联系管理员或将信息更换为身份证');
            }
            $post_data['cer_type'] = $id_type;
            $post_data['cer_num'] = $user->id_number; //证件号码
            $post_data['tel_num'] = $phone_num; //电话号码

            $processing_code = '1087'; // 4位接口编码，详见每支接口描述  快捷开户：1087
            $head_data = $this->HeadData($processing_code, $time_int);
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生问题', 'BCABCSA2');
        }
        // 调用通联接口
        try {
            $tl_data = AllInPayController::send_request($head_data, $post_data);
            if ($tl_data[0]) { // 返回成功
                $tl_res_data = $tl_data[1];
                $tl_res_response = $tl_res_data['response'];
                $tl_head_data = $tl_res_data['head'];
                $tlauth = TlAuth::create([
                    "bank_card_id" => $bank_card_id,
                    "req_trace_num" => $tl_res_response['req_trace_num'],
                    "resp_trace_num" => $tl_res_response['resp_trace_num'],
                    "trans_date" => $tl_head_data['trans_date'],
                    "processing_code" => $tl_head_data['processing_code'],
                ]);
                $bank_card->tl_auth_id = $tlauth->id; // 更新为最新的状态
                if ($bank_card->status == 2) {
                    $msg = $tl_res_response['resp_msg'] . "！请注意，当前认证状态已覆盖之前的认证状态";
                    $bank_card->status = 2;
                } else {
                    $msg = $tl_res_response['resp_msg'];
                    $bank_card->status = 2;
                }
                $bank_card->phone_num = $phone_num;
                $bank_card->save();
                return LMReturn::Success($tl_data, $msg);
            } else {
                return LMReturn::Error('调用通联接口返回错误', 'BCABCSA3', $tl_data);
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('调用通联接口时发生问题', 'BCABCSA4');
        }
    }
    /**
     * @description: 第二步：验证验证码
     * @param {Request} $request
     * @return {*}
     */
    public function BankCardTelAuth(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            // if ($tokenInfo['code'] == 400) {
            //     return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            // }
            $all = $request->all();
            $code = $all['code'];
            $bank_card_id = $all['bank_card_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCABCTA1');
        }
        // 整理 上传参数
        try {
            $bank_card = BankCard::find($bank_card_id);
            if ($bank_card->status == 3) {
                return LMReturn::Error('当前银行卡已认证', 'BCABCTA2');
            }
            $tl_auth = $bank_card->tl_auth;
            if ($tl_auth == null) {
                return LMReturn::Error('无法继续认证,请重新尝试获取验证码', 'BCABCTA6');
            }
            $time_int = time();
            $post_data['req_trace_num'] = $bank_card_id . $time_int; //2：机构请求交易流水号
            $post_data['org_processing_code '] = $tl_auth->processing_code; //原交易编码
            $post_data['org_req_trace_num'] = $tl_auth->req_trace_num; //  原交易流水号
            $post_data['org_trans_date'] = $tl_auth->trans_date; //  原交易日期
            $post_data['verify_code'] = $code; //  短信验证码
            $processing_code = '3010'; // 4位接口编码，详见每支接口描述  快捷开户：1087
            $head_data = $this->HeadData($processing_code, $time_int);
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数时发生问题', 'BCABCTA3');
        }
        // 调用通联接口
        try {
            $tl_data = AllInPayController::send_request($head_data, $post_data);
            if ($tl_data[0]) { // 返回成功
                DB::beginTransaction();
                $tl_res_data = $tl_data[1];
                $tl_res_response = $tl_res_data['response'];
                $tl_auth->sms_req_trace_num = $tl_res_response['req_trace_num'];
                $tl_auth->sms_resp_trace_num = $tl_res_response['resp_trace_num'];
                $tl_auth->save();
                $msg = $tl_res_response['resp_msg'];
                $bank_card->status = 3;
                $sign_num = $tl_res_response['sign_num'];
                $bank_card->sign_num = $sign_num;
                $user = $bank_card->user;
                $user->sign_num = $sign_num;
                $user->save();
                $bank_card->save();
                DB::commit();
                return LMReturn::Success($tl_data, $msg);
            } else {
                if ($tl_data[1] == '原交易已是终态') {
                    return LMReturn::Error('请尝试重新获取验证码进行认证', 'BCABCTA7', $tl_data);
                } else {
                    return LMReturn::Error('调用通联接口返回错误', 'BCABCTA4', $tl_data);
                }
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('调用通联接口时发生问题', 'BCABCTA5');
        }
    }
    /**
     * @description: 第三步：接收入账通知
     * @param {Request} $request
     * @return {*}
     */
    public function ToAccountNotice(Request $request)
    {
        try {
            $all = $request->all();
            $head = Request()->header();
            Log::debug(json_encode($all));
            Log::debug($head);
            // 获取到的 通联支付返回的信息
            $notic = AllInPayController::deal_request($head, $all);
            // 判断该笔交易是否存在，存在则更新，不存在则添加
            $response = $notic['response'];
            $head = $notic['head'];
            $acct_detail = json_decode($notic['acct_detail'], true);
            // return $notic;
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCABCTA1');
        }
        try {
            DB::beginTransaction();
            // 存储入账通知
            $tl_list = TlPayList::where('req_trace_num', $response['req_trace_num'])->get();
            if (count($tl_list) > 0) {
                $tl = $tl_list[0];
            } else {
                $tl = new TlPayList();
            }
            $tl->toAcctDate = $acct_detail['toAcctDate'];
            $tl->toAcctName = $acct_detail['toAcctName'];
            $tl->toAcctNo = $acct_detail['toAcctNo'];
            $tl->toAcctTime = $acct_detail['toAcctTime'];
            $tl->processing_code = $head['processing_code'];
            $tl->inst_id = $head['inst_id'];
            $tl->trans_date = $head['trans_date'];
            $tl->trans_time = $head['trans_time'];
            $tl->ver_num = $head['ver_num'];
            $tl->sign_code = $head['sign_code'];
            $tl->req_trace_num = $response['req_trace_num'];
            $sign_num = $response['sign_num'];
            $tl->sign_num =  $sign_num;
            $tl->pay_mode = $response['pay_mode'];
            $tl->bnk_id = $response['bnk_id'];
            $tl->acct_num = $response['acct_num'];
            $tl->cur_type = $response['cur_type'];
            $tl->amt_tran = $response['amt_tran'];
            $tl->resp_trace_num = $response['resp_trace_num'];
            $tl->resp_code = $response['resp_code'];
            $tl->resp_msg = $response['resp_msg'];
            $tl->pay_amount = $response['pay_amount'];
            $tl->trace_fee = $response['trace_fee'];
            $acs_summary = $response['acs_summary'];
            $tl->acs_summary = $response['acs_summary'];
            // 修改订单状态
            $order_list = Order::where('contract_no', $acs_summary)->whereIn('order_status', [-1, 1, 2])->get();
            if (count($order_list) == 1) {
                $order = $order_list[0];
                $tl->order_id = $order->id;
            } else {
                $bank_card_list = BankCard::where('sign_num', $sign_num)->whereIn('status', [2, 3])->get();
                if (count($bank_card_list) == 1) {
                    $bank_card = $bank_card_list[0];
                    $order_list = Order::where('bank_card_id',  $bank_card->id)->whereIn('order_status', [-1, 1, 2])->get();
                    if (count($order_list) == 1) {
                        $order = $order_list[0];
                        $tl->order_id = $order->id;
                    }
                }
            }

            if ($order != null) { // 如果订单不是空
                $money = 0;
                $tlpay_list = $order->tl_pay_lists;
                foreach ($tlpay_list as $tlpay) {
                    $money =  $tlpay->pay_amount + $money;
                }
                if ($money == $order->order_money) {
                    $order->investment_way = 3;
                } else {
                    $order->investment_way = 2;
                }
                $order->save();
            }
            $tl->save();
            DB::commit();
            return $tl;
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('入库发生错误', 'BCATAN1');
        }
    }
    /**
     * @description: 第四步：查询交易结果
     * @param {Request} $request
     * @return {*}
     */
    public function QueryTLOrderStatus(Request $request)
    {
        try {
            $all = $request->all();
            if (isset($all['interest_id'])) {
                $interest_id = $all['interest_id'];
            } else {
                return LMReturn::Error('未传入打款记录id');
            }
            $interest_recode = InterestRecord::find($interest_id);
            if ($interest_recode) {
                if ($interest_recode->receivable_type == 2) {
                    $receivable_no = $interest_recode->receivable_no;
                    $real_time = str_replace('-', '', date('Y-m-d', strtotime($interest_recode->real_time)));
                    if ($receivable_no == null) {
                        return LMReturn::Error('查询数据存在问题，请联系管理员检查');
                    }
                } else {
                    return LMReturn::Error('该交易非线上交易类型，无法线上交易信息');
                }
            } else {
                return LMReturn::Error('没有该记录');
            }
            $time_int = time();
            $post_data['req_trace_num'] = 'Y'.$time_int;
            $post_data['org_req_trace_num'] = $receivable_no;
            $post_data['org_trans_date'] = $real_time;
            $head_data = self::HeadData('3001', $time_int);
            $tl_data = AllInPayController::send_request($head_data, $post_data);
            return LMReturn::Success($tl_data);
        } catch (\Throwable $th) {
            return LMReturn::Error('参数存在问题', 'BCABCTA1');
        }
    }

    // 通联回款（做成方法，在正常回款时通联认证的调用）待打款->打款中
    public static function ReceivableFun($interest_record_id) {
        $interest_record = InterestRecord::where('id', $interest_record_id)->with('order.bank_card.bank')->first();
        if ($interest_record) {
            if ($interest_record->order->bank_card->status != 3 || $interest_record->order->bank_card->sign_num == null) {
                return '未通过通联认证或无通联会员号，不支持线上回款';
            }
            $pay_money = $interest_record->payment_amount;
            $balance_data = self::CheckBalance();
            $available_amt = 0;
            $sep_acct_num = env('SEP_ACCT_NUM');
            foreach ($balance_data as $balance_datum) {
                if ($balance_datum['acct_num'] == $sep_acct_num) {
                    $available_amt = $balance_datum['available_amt']/100;
                }
            }
            if ($available_amt < $pay_money) {
                return '余额不足，请联系管理员充值';
            }
            $sign_num = $interest_record->order->bank_card->sign_num;
            $bnk_id = $interest_record->order->bank_card->bank->bnk_id;
            $acct_num = $interest_record->order->bank_card->bank_num;
            $time_int = time();
            $post_data['req_trace_num'] = $interest_record_id . 'R' . $time_int; //2：机构请求交易流水号
            $post_data['bnk_id'] = $bnk_id;      //  03040000测试用华夏银行
            $post_data['sign_num'] = $sign_num;     //  通联会员号
            $post_data['charge_flag'] = 0;          // 账户标识
            $post_data['repayment_type'] = 0;       // 还款类型
            $post_data['acct_type'] = 1;            // 账户类型
            $post_data['acct_num'] = $acct_num;     // 账号
            $post_data['pay_mode'] = 2;             // 支付模式
            $post_data['cur_type'] = 156;           // 币种，人民币
            $post_data['amt_tran'] = $pay_money*100;
            $sep_detail = [
                'sep_no'=>'000',
                'sep_acct_type'=>'1',
                'sep_bank_id'=>env('SEP_BANK_ID'),
                'sep_acct_num'=>$sep_acct_num,
                'sep_trans_amount'=>$pay_money*100
            ];
            $post_data['sep_detail'] = $sep_detail;
            $post_data['prod_import_flag'] = 0;
            $post_data['resp_url'] = env('COMMON_NOTIFY') . '/tl/pay/NotifyFun';
            $processing_code = '2294';
            $head_data = self::HeadData($processing_code, $time_int);
            $tl_data = AllInPayController::send_request($head_data, $post_data);
            if ($tl_data[0]) {
                $interest_record->receivable_type = 2;
                $interest_record->receivable_no = $interest_record_id . 'R' . $time_int;
                $interest_record->save();
                return 1;
            } else {
                return $tl_data[1];
            }
        } else {
            return '无该记录';
        }
    }

    // 还款回调数据解密
    public static function NotifyDecryption($repMsg) {
        $result = base64_decode($repMsg);
        //第二步，获取其中的三个值(先替换，转数组)
        $result = str_replace('<STSPackage><EncryptedText>', '', $result);
        $result = str_replace('</EncryptedText>', ',', $result);
        $result = str_replace('<KeyInfo><ReceiverX509CertSN>', '', $result);
        $result = str_replace('</ReceiverX509CertSN><EncryptedKey>', ',', $result);
        $result = str_replace('</EncryptedKey></KeyInfo></STSPackage>', '', $result);
        $result_arr = explode(',', $result);
        $encryptedText = $result_arr[0];
        $receiverX509CertSN = $result_arr[1];
        $encryptedKey = $result_arr[2];

        //第三步,先Base64解码对称密钥的密文，再用自己的私钥解密，获得原对称密钥，解密算法为RSA/ECB/PKCS1Padding；
        $encryptedKey = base64_decode($encryptedKey);
        $response = AllInPayController::decryptByPrivateKey($encryptedKey, '../app/Http/Controllers/AllInPay/wts-111111.pfx', '111111');
        //第四步,再用Base64解码报文密文，再用对称密钥解密Base64解码后的报文，获得报文明文，解密算法为DESede/ECB/PKCS5Padding；
        $encryptedText = base64_decode($encryptedText);
        $oldReponse = $response = $response = AllInPayController::decrypt($encryptedText, $response);
        //第五步,截取字符串
        $end = stripos($response, "</transaction>");
        $response = substr($response, 0, $end) . "</transaction>";
        $response = iconv("UTF-8", "gb2312//TRANSLIT", $response);
        $response = AllInPayController::xmlToArray($response);
        $sign_code = $response['head']['sign_code'];

        $newStr = str_replace('<sign_code>' . $sign_code . '</sign_code>', '', $oldReponse);
        $endTwo = stripos($newStr, "</transaction>");
        $newStr = substr($newStr, 0, $endTwo) . "</transaction>";
        $return_arr = AllInPayController::xmlToArray(iconv("UTF-8", "gb2312//TRANSLIT", $newStr));
        //第六步，SHA1withRSA验签
        $sign_code = base64_decode($sign_code);
        $response = AllInPayController::verify($newStr, $sign_code, file_get_contents('../app/Http/Controllers/AllInPay/wts.cer'));
        if ($response && $return_arr['response']) {
            if (
                $return_arr['response']['resp_code'] == '0000' ||
                $return_arr['response']['resp_code'] == '1111' ||
                $return_arr['response']['resp_code'] == '1112' ||
                $return_arr['response']['resp_code'] == '4444'
            ) {
                return [true, $return_arr]; //成功
            }
            return [false, $return_arr['response']['resp_msg']];
        }
        return [false, $return_arr['response']['resp_msg']];
    }

    // 还款回调地址(已完成，需优化代码)
    public function NotifyFun(Request $request) {
        $all = $request->all();
        $repMsg = $all['repMsg'];
        $resultMsg = self::NotifyDecryption($repMsg);
        if ($resultMsg[0]) {
            $response = $resultMsg[1]['response'];
            $req_trace_num = $response['req_trace_num'];
            $interest_record_id = explode('R', $req_trace_num)[0];
            $interest_record = InterestRecord::where('id', $interest_record_id)->with('order.bank_card.bank')->with('order.user')->first();
            if ($interest_record) {
                if ($interest_record->receivable_type = 2) {
                    try {
                        DB::beginTransaction(); //开启事务
                        if ($interest_record->status != 2) {
                            DB::rollback(); //数据库回滚
                            $order_record = OrderRecord::create([
                                "audit_step" => 0, //审核的步骤   1初审  2复审 0不是审核
                                "order_id" => $interest_record->order_id,
                                "type" => 0, // 1是审核 2是订单生成   3是订单修改   4订单转移  5财务 6出纳
                                "ir_id" => $interest_record->id,
                                "is_success" => '2', //  1通过/成功 2拒绝/失败
                                "remark" => '通联打款状态异常，请检查资金是否到账'.date('Y-m-d H:i:s', time())
                            ]);
                            return LMReturn::Error('打款状态异常', 'OPCBOPC1', $order_record);
                        }
                        $interest_record->status = 3;
                        $interest_record->interest_money = $response['pay_amount']/100;
                        $interest_record->real_time = date('Y-m-d H:i:s', time());
                        $interest_record->bank_num = $interest_record['order']['bank_card']['bank_num'];
                        $interest_record->open_bank = $interest_record['order']['bank_card']['bank_sum_name'];
                        $interest_record->user_name = $interest_record['order']['user']['name'];
                        $interest_record->account_name = $interest_record['order']['bank_card']['account_name'];
                        $interest_record->bank_name = $interest_record['order']['bank_card']['bank']['bank_name'];
                        $order = $interest_record->order;
                        $shouldMoney = $interest_record->money + $interest_record->interest;
                        $num = $shouldMoney - $response['pay_amount']/100;
                        if ($num < 10.0 && $num > -10.0) {
                            if ($interest_record->num == $interest_record->num_all || $interest_record->type == 3) { // 如果是最后一期 处理订单状态 和本金验证
                                $order->order_status = 6;
                                if ($interest_record->money != $order->order_money) { // 本金验证是否一致
                                    DB::rollback(); //数据库回滚
                                    $order_record = OrderRecord::create([
                                        "audit_step" => 0, //审核的步骤   1初审  2复审 0不是审核
                                        "order_id" => $interest_record->order_id,
                                        "type" => 0, // 1是审核 2是订单生成   3是订单修改   4订单转移  5财务 6出纳
                                        "ir_id" => $interest_record->id,
                                        "is_success" => '2', //  1通过/成功 2拒绝/失败
                                        "remark" => '出纳因为金额异常导致出纳失败，请检查资金是否到账'.date('Y-m-d H:i:s', time())
                                    ]);
                                    return LMReturn::Error('订单金额异常', 'OPC012', $order_record);
                                }
                            }
                            $order->save();
                            $interest_record->save();
                            $interest_id = $interest_record->id;
                            $pay = new FamiliesMoneyRecord();
                            $pay->interest_id = $interest_id;
                            $pay->families_id = 1;
                            $pay->order_id = $order->id;
                            $pay->worker_id = $order->worker_id;
                            $pay->branch_id = $order->branch_id;
                            $money = $response['pay_amount']/100;
                            $pay->money =  0 - $money;
                            $pay->course_money = 0;
                            $pay->pay_type =  4;
                            $pay->real_time =  $interest_record->real_time;
                            $pay->type =  2; // 1订单收款 2还本付息 3费用报销
                            $pay->status =  5; // 1审核中  2通过/待打款  3拒绝 4打款中 5已付款
                            $pay->save();
                            $order_record = OrderRecord::create([
                                "audit_step" => 0, //审核的步骤   1初审  2复审 0不是审核
                                "order_id" => $interest_record->order_id,
                                "type" => 6, // 1是审核 2是订单生成   3是订单修改   4订单转移  5财务 6出纳
                                "ir_id" => $interest_record->id,
                                "is_success" => '1', //  1通过/成功 2拒绝/失败
                                "remark" => '通联出纳成功'.date('Y-m-d H:i:s', time())
                            ]);
                            DB::commit(); //提交至数据库
                            return LMReturn::Success($order_record, '订单打款成功');
                        } else {
                            DB::rollback(); //数据库回滚
                            $order_record = OrderRecord::create([
                                "audit_step" => 0, //审核的步骤   1初审  2复审 0不是审核
                                "order_id" => $interest_record->order_id,
                                "type" => 0, // 1是审核 2是订单生成   3是订单修改   4订单转移  5财务 6出纳
                                "ir_id" => $interest_record->id,
                                "is_success" => '2', //  1通过/成功 2拒绝/失败
                                "remark" => '实际打款金额与应打款金额差距过大，请检查资金到账情况'.date('Y-m-d H:i:s', time())
                            ]);
                            return LMReturn::Error('实际打款金额与应打款金额差距过大', 'OPC007', $order_record);
                        }
                    } catch (\Throwable $th) {
                        DB::rollback(); //数据库回滚
                        $order_record = OrderRecord::create([
                            "audit_step" => 0, //审核的步骤   1初审  2复审 0不是审核
                            "order_id" => $interest_record->order_id,
                            "type" => 0, // 1是审核 2是订单生成   3是订单修改   4订单转移  5财务 6出纳
                            "ir_id" => $interest_record->id,
                            "is_success" => '2', //  1通过/成功 2拒绝/失败
                            "remark" => '订单进入打款状态失败，请检查资金到账情况'.date('Y-m-d H:i:s', time())
                        ]);
                        return LMReturn::Error('订单进入打款状态失败', 'OPC008', $order_record);
                    }
                }
            }
        }
        return LMReturn::Success();
    }

    // 资金余额查询接口
    public function CheckBalanceFace(Request $request) {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        return LMReturn::Success(self::CheckBalance());

    }

    // 通联资金余额查询
    public static function CheckBalance() {
        $time_int = time();
        $post_data['req_trace_num'] = 'C'.$time_int; //2：机构请求交易流水号
        $post_data['sign_num'] = env('SIGN_NUM');     //  通联会员号
        $head_data = self::HeadData('3002', $time_int);
        $tl_data = AllInPayController::send_request($head_data, $post_data);
        if ($tl_data[0]) {
            $response = $tl_data[1]['response'];
            return json_decode($response['qur_rst'], true);
        } else {
            return null;
        }
    }

    /**
     * @description: 公共方法：构建请求头
     * @param {Request} $request
     * @return {*}
     */
    public static function HeadData($processing_code, $time_int)
    {
        $head_data['processing_code'] = $processing_code; // 4位接口编码，详见每支接口描述  快捷开户：1087
        $head_data['ver_num'] = '1.00'; // 版本号
        $head_data['inst_id'] = env('INST_ID'); // 通联分配的机构编码
        $head_data['trans_date'] = date('Ymd', $time_int); // 数据格式yyyyMMdd
        $head_data['trans_time'] =  date('His', $time_int);; // 数据格式HH24MMSS
        return $head_data;
    }

    // 文件联机下载，交易信息
    public function RecordFile(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        if (isset($tokenInfo['worker_id'])) {
            $worker_id = $tokenInfo['worker_id'];
            if (FddUtils::IsWorkerRole($worker_id) == false) {
                return LMReturn::Error('只有超级管理员才能查看');
            }
        } else {
            return LMReturn::Error('登录信息有误');
        }
        $all = $request->all();
        if (isset($all['file_type'])) {
            $file_type = $all['file_type'];
        } else {
            return LMReturn::Error('请选择文件类型');
        }
        $date = $all['trans_date'] ?? Carbon::yesterday()->toDateString();
        $trans_date = str_replace('-', '', $date);
        $post_data['inst_id'] = env('INST_ID');
        $post_data['trans_date'] = $trans_date;
        $post_data['file_type'] = $file_type;
        $batch_no = '81370000_JR_'.$trans_date.'_01';
        $post_data['batch_no'] = $batch_no;
        $code = '81370000'.$trans_date.$file_type.$batch_no;
        $privateKey = file_get_contents("../app/Http/Controllers/AllInPay/wts-111111.pfx"); //（pfx文件）
        $sign_code = AllInPayController::genSign($code, $privateKey);
        $post_data['sign_code'] = $sign_code;
        $url = 'http://116.228.64.55:28082/ccdp-acquire-web/service/orgDownloadReconFile.action';
        return AllInPayController::send_post($url, $post_data);
    }

    // 更换手机号（通联已备案暂未启用）
    public function UplodTel(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $post_data = [];
        $time_int = time();
        $post_data['req_trace_num'] = 'U'.$time_int; //2：机构请求交易流水号
        $post_data['sign_num'] = '';     //  通联会员号
        $post_data['bnk_id'] = '';
        $post_data['acct_type'] = '1';
        $post_data['acct_num'] = '';
        $post_data['tel_num'] = '';
        $post_data['org_tel_num'] = '';
        $head_data = self::HeadData('1090', $time_int);
        $tl_data = AllInPayController::send_request($head_data, $post_data);
        return $tl_data;
    }

}
